<?php

namespace App\Http\Controllers\Front;

use App\Http\Controllers\Controller;
use App\Model\Cards;
use App\Model\MaibaoOrder;
use App\Model\Places;
use App\Model\UserBill;
use App\Model\UserDetail;
use App\Model\UserGrade;
use App\Model\UserRecharge;
use App\Model\UserTemplate;
use App\Model\UserTemplateClone;
use App\Model\UserTemplateOrder;
use App\Model\UserWalletRecordLog;
use App\Model\UserWeixinPayCallBackErrorLog;
use App\Model\VipFeeConfig;
use App\Model\WeChat;
use App\Tool\Util;
use App\User;
use Carbon\Carbon;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Psr\SimpleCache\InvalidArgumentException;


/**
 * Class WeChatController
 * @package App\Http\Controllers\Front
 */
class WeChatController extends Controller
{
    /**
     * 微信消息通知
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     * @throws \EasyWeChat\Kernel\Exceptions\BadRequestException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \ReflectionException
     */
    public function server(Request $request)
    {
        $app = WeChat::getWeChatOfficialAccount();
        $user = $app->user;
        $app->server->push(
            function ($message) use ($user) {
                switch ($message['MsgType']) {
                    case 'event':
//                    \Log::info($message);
                        if ($message['Event'] == 'subscribe') {
                        $user_detail = UserDetail::where('open_id', $message['FromUserName'])->first();
                        $user_detail->subscribe = 1;
                        $user_detail->save();
                            return '和上万微信好友互推，点这里！<a href="http://weixin.51huimaibao.cn/#/tools/circle/index">汇脉宝互推圈</a>';
                        }

                        if ($message["Event"] == "unsubscribe"){
                            $user_detail = UserDetail::where('open_id', $message['FromUserName'])->first();
                            $user_detail->subscribe = 0;
                            $user_detail->save();
                        }

                        break;
                    case 'text':
                        if ($message['Content'] == "吸粉") {
                            return '【微信精准客户引流】链接：https://pan.baidu.com/s/1rmYT7iQn7alqKWP98hb7ww   密码：92gf';
                        } elseif ($message["Content"] == "人脉") {
                            return '【超级人脉术】限时7天失效链接：https://pan.baidu.com/s/1PXDmZCd-ZC7_dWnX2kh16A  密码：gnrs（建议在电脑用百度网盘下载观看）';
                        } elseif ($message["Content"] == '海报') {
                            $weChat = new WeChat();
                            $activity_media_id = $weChat->getUserCode($message['FromUserName']);
                            if (!$activity_media_id){
                                $url =  env('weixinUrl');
                                return '请进入邀请好友注册页面'.$url."/#/user/reward";
                            }
                            return new \EasyWeChat\Kernel\Messages\Image($activity_media_id);
                        } elseif ($message['Content'] == "互推") {
                            return new  \EasyWeChat\Kernel\Messages\Image(env("yuHuiMedia"));
                        }
                        break;
                    case 'image':
                        return '收到图片消息' . $message['PicUrl'];
                        break;
                    case 'voice':
                        return '收到语音消息';
                        break;
                    case 'video':
                        return '收到视频消息';
                        break;
                    case 'location':
                        return '收到坐标消息';
                        break;
                    case 'link':
                        return '收到链接消息';
                        break;
                    // ... 其它消息
                    default:
                        return '收到其它消息';
                        break;
                }
            });
        $response = $app->server->serve();
        return $response;
    }

    /**
     * 创建菜单
     */
    public function createMenu()
    {
        $app = WeChat::getWeChatOfficialAccount();

        $buttons = [
            [
                "type" => "view",
                "name" => "了解我们",
                "url" => "https://mp.weixin.qq.com/mp/homepage?__biz=MzU4MTU0NjAwNA%3D%3D&hid=1&sn=94938c1c645f0470d44a80091c0f6432"
            ], [
                "type" => "view",
                "name" => "汇营天下",
                "url" => env('weixinUrl')
            ],
            [
                "name" => "近期活动",
                "sub_button" => [
                    [
                        "type" => "view",
                        "name" => "小测试",
                        "url" => env("apiUrl") . "/front/oauth?user_id=1"
                    ],
                ],
            ],

        ];

        return $app->menu->create($buttons);

    }

    /**
     * 获取菜单
     */
    public function getMenu()
    {
        $app = WeChat::getWeChatOfficialAccount();

        dd($app->menu->list());
    }

    /**
     * 删除菜单
     */
    public function delMenu()
    {
        $app = WeChat::getWeChatOfficialAccount();
        $app->menu->delete();
    }

    public function getWeChatUserList()
    {
        $app = WeChat::getWeChatUserListAll();
        dd($app);
    }

    public function getWeChatUser(Request $request)
    {
        $open_id = $request->input('open_id');

        $user_info = WeChat::getWeChatUser($open_id);
        var_dump($user_info);
    }

    /**
     * 微信网页授权
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function oauth(Request $request)
    {
        $redirect = $request->input("redirect");
        $app = WeChat::getWeChatOfficialAccount();
        $user_id = $request->input('user_id');
        // 海报活动注册
        $activity = $request->input('poster');

        return  $app->oauth->with(['state' => $user_id . ',' . $redirect . ',' . $activity])->redirect();
    }


    /**
     * 网页授权回调地址
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function oauth_callback()
    {
        $value = $_REQUEST['state'];
        $value = explode(",", $value);
        $user_id = $value[0];  // 推荐用户
        $redirect = $value[1]; // 回调地址
        $activity = $value[2]; // 活动类型

        $app = WeChat::getWeChatOfficialAccount();
        $weChatUser = $app->oauth->user(); // 网页授权信息
        $subscribe  =  $app->user->get($weChatUser['original']['openid']);
        $subscribe  =   $subscribe["subscribe"]; // 是否关注微信公众号
        $open_id = $weChatUser['original']['openid'];
        $user_info = $weChatUser['original'];
        $user_detail = UserDetail::where('union_id', $user_info["unionid"])->first();
        // 回调处理
        switch ($user_detail) {
            case $user_detail == 'NULL': // 新用户
                if (preg_match("/^\d*$/", $user_id) == true && $user_id != "") {
                    // 会员推荐会员 返回会员的名片
                    $user_deatil_data = [
                        'wechat_name' => isset($user_info['nickname']) ? $user_info['nickname'] : '',
                        'head_portrait' => isset($user_info['headimgurl']) ? $user_info['headimgurl'] : '',
                        'open_id'  => $open_id,
                        'union_id' => $user_info["unionid"],
                        'subscribe' => $subscribe,
                    ];
                    $user = new User();
                    $user->type = 4;
                    $user->from_type = $activity;
                    $user->save();
                    $user->detail()->save(new UserDetail($user_deatil_data));
                    if($activity){
                      return   header( 'Location:' . env('weixinUrl') . '/#/activity/invite/' . '?open_id= ' . $user->id .'&user_id='.$user_id.'&subscribe='.$subscribe. '&redirect=' . $redirect);
                    }else{
                        return   header( 'Location:' . env('weixinUrl') . '/#/register' . '?open_id= ' . $user->id .'&user_id='.$user_id.'&subscribe='.$subscribe. '&redirect=' . $redirect);
                    }
                } else {
                    //会员自己进入平台
                    $user_deatil_data = [
                        'wechat_name' => $user_info['nickname'],
                        'head_portrait' => $user_info['headimgurl'],
                        'open_id' => $open_id,
                        'union_id' => $user_info["unionid"],
                        'subscribe' => $subscribe,
                    ];
                    $user = new User();
                    $user->type = 4;
                    $user->save();
                    $user->detail()->save(new UserDetail($user_deatil_data));
                    return header('Location:' . env('weixinUrl') . '/#/register' . '?open_id= ' . $user->id .'&subscribe='.$subscribe. '&redirect=' . $redirect);
                }
                break;
            case
                $user_detail != 'NULL':  // 注册过的用户
                $user_detail->wechat_name = $user_info['nickname'];
                $user_detail->head_portrait = $user_info['headimgurl'];
                $user_detail->open_id = $open_id;
                $user_detail->union_id = $user_info["unionid"];
                $user_detail->subscribe = $subscribe;
                $user_detail->save();
                if($activity){
                    return   header( 'Location:' . env('weixinUrl') . '/#/activity/invite/' . '?open_id= ' . $user_detail->user_id .'&user_id='.$user_id.'&subscribe='.$subscribe. '&redirect=' . $redirect);
                }else{
                    return   header( 'Location:' . env('weixinUrl') . '/#/register' . '?open_id= ' . $user_detail->user_id .'&user_id='.$user_id.'&subscribe='.$subscribe. '&redirect=' . $redirect);
                }
//                return header('Location:' . env('weixinUrl') . '/#/register?open_id=' . $user_detail->user_id .'&user_id='.$user_id.'&subscribe='.$subscribe. '&redirect=' . $redirect);
                break;
        }
        return "回调失败！";
    }

    public function user_grade(User $user, $user_grade_id)
    {
        $grade_user = User::where("id", $user_grade_id)->first();
        $user->pid = $grade_user->id;
        $user->salesman_id = $grade_user->type == 3 ? $grade_user->id : $grade_user->salesman_id;
        $user->operator_id = $grade_user->operator_id;
        $user->place_partner_id = $grade_user->place_partner_id;
        $user->enterprise_user_id = $grade_user->enterprise_user_id;
        $user->save();

    }

    /**
     * @param $user_id
     * @param $refereeUser
     * @return array
     *
     * 会员等级推理图
     * -------------------------------------------------------------------------------------------------
     * 会员   一级会员    二级会员    一级业务员   二级业务员   三级业务员       运营  城市合伙人
     *  A        0           0            Z            0            0          X       Y
     * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
     *  B        A           0            0            Z            0          X       Y
     *  C        B           A            0            0            Z          X       Y
     *  D        C           B            0            0            Z          X       Y
     *  ...
     * -------------------------------------------------------------------------------------------------
     *  E        0           0             0           0            0          0        0
     *  F        E           0             0           0            0          0        0
     *  G        F           E             0           0            0          0        0
     *  ....
     * -------------------------------------------------------------------------------------------------
     */
    public function getUserFrom($user_id, $refereeUser)
    {
        if ($refereeUser->type == 3) {
            $user_From_data = [
                'one_user_id' => 0,
                'two_user_id' => 0,
                'one_salesman_id' => $user_id,
                'two_salesman_id' => 0,
                'three_salesman_id' => 0,
                'operator_id' => $refereeUser->salesmen->operator_id,
                'place_partner_id' => $refereeUser->salesmen->place_partner_id
            ];
        } else {
            $refereeUserFrom = $refereeUser->userFrom;
            $user_From_data = [
                'one_user_id' => $refereeUser->id,
                'two_user_id' => isset($refereeUserFrom->one_user_id) ? $refereeUserFrom->one_user_id : 0,
                'one_salesman_id' => 0,
                'two_salesman_id' => isset($refereeUserFrom->one_salesman_id) ? $refereeUserFrom->one_salesman_id : 0,
                'three_salesman_id' => $this->getUserFromThreeSalesmanId($refereeUserFrom),
                'operator_id' => isset($refereeUserFrom->operator_id) ? $refereeUserFrom->operator_id : 0,
                'place_partner_id' => isset($refereeUserFrom->place_partner_id) ? $refereeUserFrom->place_partner_id : 0
            ];

        }
        return $user_From_data;

    }

    /**
     * 获取三级 业务员
     * @param $refereeUserFrom
     * @return int
     */
    public function getUserFromThreeSalesmanId($refereeUserFrom)
    {
        if (isset($refereeUserFrom->two_salesman_id)) {
            return $refereeUserFrom->two_salesman_id;
        } elseif (isset($refereeUserFrom->three_salesman_id)) {
            return $refereeUserFrom->three_salesman_id;
        } else {
            return 0;
        }
    }


    /**
     * 生成二维码
     * @param Request $request
     * @return string|void
     */
    public function getQrCode(Request $request)
    {

        $this->validate($request, ['user_id' => 'required'], [
            'required' => ':attribute不能为空',
        ], ['user_id' => 'user_id']);

        $user_id = $request->input('user_id');

        $user = User::where('id', $user_id)->first();

        $userCard = Cards::where('user_id', $user_id)->first();
        // todo
//        if (isset($user->qr_code)) {
//            $date = [
//                'qr_code' => $user->qr_code,
//                'head_picture' => $userCard->head_picture,
//                'user_name' => $userCard->user_name,
//                'province' => Places::getPlacesName($userCard->province),
//                'city' => Places::getPlacesName($userCard->city),
//                'area' => Places::getPlacesName($userCard->area),
//                'address_detail' => $userCard->address_detail,
//            ];
//            return $this->renderJson($date);
//        }
        $weChat = new WeChat();
        $qr_code = $weChat->saveUserHeadPortrait($user, $userCard->head_picture, 200);
        $date = [
            'qr_code' => $qr_code,
            'head_picture' => $userCard->head_picture,
            'user_name' => $userCard->user_name,
            'province' => isset($userCard->province) ? Places::getPlacesName($userCard->province) : '',
            'city' => isset($userCard->city) ? Places::getPlacesName($userCard->city) : '',
            'area' => isset($userCard->area) ? Places::getPlacesName($userCard->area) : '',
            'address_detail ' => isset($userCard->address_detail) ? $userCard->address_detail : '',
        ];

        return $this->renderJson($date);
    }

    public function codePath()
    {

    }

    /**
     * 微信支付
     * @param Request $request
     * @return string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function weChatPayment(Request $request)
    {
        $user = Auth::user();

        $vip_fee_config_id = $request->input('vip_fee_config_id');
        $vipFeeConfig = VipFeeConfig::where('id', $vip_fee_config_id)->first();
        $app = WeChat::getWeChatOfficialAccount();
        $url = env('weixinUrl') . '/#/pay/vip';
        $app->jssdk->setUrl($url);
        $jssdk = $app->jssdk->buildConfig(array('chooseWXPay'), false, false, false);
        $out_trade_no = Util::getOrderNum();
        $data = [
            'appId' => $jssdk['appId'],
            'mch_id' => '1453941402',
            'nonce_str' => $jssdk['nonceStr'],
            'sign' => $jssdk['signature'],
            'out_trade_no' => $out_trade_no
        ];
        $money = $this->updateUserGradeDate($user, $vipFeeConfig, $data);

        if ($money == 'expire') {
            return response()->json(['status' => -1, 'message' => '会员没有到期不能重复购买']);
        } elseif ($money == 'fail') {
            return response()->json(['status' => -1, 'message' => '支付日记保存失败']);
        }
//        $money = 0.01;
        $weChatConfig = WeChat::getWeChatPayment();
        $result = $weChatConfig->order->unify([
            'body' => $vipFeeConfig->name,
            'out_trade_no' => $out_trade_no,
            'total_fee' => $money * 100,
//            'total_fee' => 1,
            'trade_type' => 'JSAPI',
            'openid' => $user->detail->open_id,
        ]);
//        var_dump ($result);die;
        if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
            $prepayId = $result['prepay_id']; // 这个很重要。有了这个才能调用支付。
        } else {
            \Log::error($result);
            return response()->json($result, -1, '微信服务器订单生成失败！');
        }
        $config = $weChatConfig->jssdk->bridgeConfig($prepayId, false);
        return json_encode(['jsSdk' => $jssdk, 'payConfig' => $config]);

    }

    /**
     * 支付记录
     * @param User $user 付款会员
     * @param VipFeeConfig $vipFeeConfig 购买的产品
     * @param $data  array 微信配置数据
     * @return float|\Illuminate\Http\JsonResponse
     */
    public function updateUserGradeDate($user, $vipFeeConfig, $data)
    {

        $paymentTime = date("Y-m-d H:i:s");
        $overed_at = date("Y-m-d H:i:s", strtotime("+" . $vipFeeConfig->months . "month", strtotime($paymentTime)));
        $last_time_date = date("Y-m-d H:i:s", strtotime("+3 day", strtotime($overed_at)));
        $item = [
            'app_id' => $data['appId'],
            'mch_id' => $data['mch_id'],
            'nonce_str' => $data['nonce_str'],
            'sign' => $data['sign'],
            'out_trade_no' => $data['out_trade_no'],
            'status' => (bool)0,
            'pay_type' => '微信支付',
            'pay_time' => $paymentTime,
            'is_pay' => (bool)0,
            'user_id' => $user->id,
            'last_at' => $last_time_date,
            'overed_at' => $overed_at,
            'vip_fee_config_comment' => $vipFeeConfig->name,
            'vip_fee_config_id' => $vipFeeConfig->id
        ];
        $user_grade = $user->userGrade;

        if ($user_grade == NULL || $user_grade == false || $user_grade == '') {
            $item['money'] = $vipFeeConfig->money;
            if ($vipFeeConfig->type == 1) {
                //1没有用户等级 ,生成订单user_recharges
                $item['last_money'] = $vipFeeConfig->money - 10;
            } else {
                //2没有用户等级 ,生成订单user_recharges
                $item['last_money'] = $vipFeeConfig->money;
            }
        } else {
            // 判断user_grade的last_at和当前时间比是否过期了，如果过期了就读取vip_fee_config表的money
            if ($user_grade->overed_at > $paymentTime) {
                return 'expire';
            }

            $user_grade_vipFeeConfig = VipFeeConfig::where('id', $user_grade->vip_fee_config_id)->first();
            if ($vipFeeConfig->type == 1 && $user_grade->last_at > $paymentTime && $vipFeeConfig->type = $user_grade_vipFeeConfig->type) {
                $money = $user_grade->last_money > $vipFeeConfig->last_money ? $user_grade->last_money : $vipFeeConfig->last_money;
                $item['money'] = $money;
                $item['last_money'] = $money - 10;
            } else {
                $item['money'] = $vipFeeConfig->money;
                $item['last_money'] = $vipFeeConfig->money;
            }
        }
        $user_recharge = new  UserRecharge();
        $res = $user_recharge->add($item);
        if (!$res) {
            \Log::info(['pay_error' => '支付日志记录失败']);
            return 'fail';
        }
        return $item['money'];
    }

    /**
     * 微信支付异步返回数据
     */
    public function callBack()
    {
        $weixinCallBackMessage = file_get_contents("php://input");
//        file_put_contents('./1.txt', $weixinCallBackMessage);
//        $weixinCallBackMessage = file_get_contents('./1.txt');
        $callBackArray = Util::xml_to_array($weixinCallBackMessage);
        if ($callBackArray['return_code'] !== 'SUCCESS' && $callBackArray['result_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态 // result_code用户是否支付成功
            return $this->error();
        }
        $out_trade_no = $callBackArray['out_trade_no']; // 微信支付订单号

        // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
        $rechargeObj = UserRecharge::where('out_trade_no', $out_trade_no)->where('is_pay', '0')->first();

        if (!$rechargeObj) {
            return $this->error(); // 查询是否有该订单如果没有就直接返回false
        }

        // 修改订单状态
        try {
            \DB::beginTransaction();
            $this->callBackStatus($rechargeObj, $callBackArray);
            \DB::commit();
        } catch (\Exception $e) {
            \DB::rollBack();
            // 记录错误日志
            $error_log = new UserWeixinPayCallBackErrorLog();
            $error_log->insert(['error' => $e->getMessage()]);
            return $this->error();
        }
        Cache::forget('profile-' . $rechargeObj->user_id);
        return $this->success();
    }

    /**
     * 微信支付修改数据库状态并记录日志和返佣状态
     * @param $rechargeObj
     * @throws \Exception
     */
    public function callBackStatus($rechargeObj, $callBackArray = '')
    {
        $date = date('Y-m-d H:i:s');
        // 修改支付状态
        $rechargeObj->is_pay = 1;
        $rechargeObj->status = 1;
        $rechargeObj->pay_time = $date;
        $rechargeObj->weixin_total_fee = $callBackArray['total_fee'] * 0.01;
        $update_message = $rechargeObj->save();
        if ($update_message == false) throw new \Exception('状态修改失败');

        // 查询会员级别表中是否有user_id
        $userGradeObj = UserGrade::where('user_id', $rechargeObj->user_id)->first();
        if ($userGradeObj == null) {
            $userGradeModel = new UserGrade();
            $userGradeModel->user_id = $rechargeObj->user_id;
            $userGradeModel->last_money = $rechargeObj->last_money;
            $userGradeModel->vip_fee_config_id = $rechargeObj->vip_fee_config_id;
            $userGradeModel->vip_fee_config_comment = $rechargeObj->vip_fee_config_comment;
            $userGradeModel->overed_at = $rechargeObj->overed_at;
            $userGradeModel->last_at = $rechargeObj->last_at;
            $userGradeModel->created_at = $date;
            $add_user_grade = $userGradeModel->save();
            if ($add_user_grade == false) throw new \Exception('add_user_grade error');
        } else {
            $userGradeObj->user_id = $rechargeObj->user_id;
            $userGradeObj->last_money = $rechargeObj->last_money;
            $userGradeObj->vip_fee_config_id = $rechargeObj->vip_fee_config_id;
            $userGradeObj->vip_fee_config_comment = $rechargeObj->vip_fee_config_comment;
            $userGradeObj->overed_at = $rechargeObj->overed_at;
            $userGradeObj->last_at = $rechargeObj->last_at;
            $userGradeObj->updated_at = $date;
            $update_user_grade = $userGradeObj->save();
            if ($update_user_grade == false) throw new \Exception('update_user_grade error');
        }

        // 会员钱包记录总表
        $UserWalletRecordLog = new UserWalletRecordLog();
        $UserWalletRecordLog->user_id = $rechargeObj->user_id;
        $UserWalletRecordLog->money = $rechargeObj->money;
        $UserWalletRecordLog->type = 4;
        $UserWalletRecordLog->income_type = 0;
        $UserWalletRecordLog->title = $rechargeObj->vip_fee_config_comment;
        $UserWalletRecordLog->save();

        // 会员充值分销返佣和企业返佣
        $u = new UnifiedReturnCommissionController();
        $u->UnifiedReturnCommission($rechargeObj->user_id, $rechargeObj->out_trade_no);
    }

    /**
     * 获取微信jssdk 配置
     * @param Request $request
     * @return string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */

    public function getWeChatJsSdkConfig(Request $request)
    {
        $url = $request->input('url');
        $share = $request->input('share');
        $app = WeChat::getWeChatOfficialAccount();
        $app->jssdk->setUrl($url);
        $jssdk = $app->jssdk->buildConfig(array($share), false, false, false);
        return json_encode(['jsSdk' => $jssdk]);
    }

    public function getWeChatConfig()
    {
        $app = WeChat::getWeChatOfficialAccount();

        try {
            $ticket = $app->jssdk->getTicket ();
        } catch (InvalidConfigException $e) {
            \Log::error ($e);
        } catch (InvalidArgumentException $e) {
            \Log::error ($e);
        }
        $options = \Config::get('wechat');
        return $this->renderJson(['config' => $options['official_account']['default'], "ticket" => $ticket]);
    }

    public function sendWeChatMsg(Request $request)
    {
        $open_id = $request->input('open_id');
        $app = WeChat::getWeChatOfficialAccount();
        $app->template_message->send([
            'touser' => $open_id,
            'template_id' => 'dI5EA694jO7c1I-y9B9wlGNNHDM-akRTE9WxyoVUbmg',
            'data' => [
                'first' => '恭喜你购买成功',
                'keyword1' => '2018年新款情趣蕾丝连衣裙',
                'keyword2' => '128元',
                'keyword3' => '2',
                'remark' => '欢迎再次购买,帅哥!'
            ],
        ]);
    }

    public function answerImage(Request $request)
    {
        $this->validate($request, [
            'sex' => 'required',
            'open_id' => 'required'
        ], [
            'required' => ':attribute不能为空'
        ], [
            'sex' => '性别',
            'open_id' => 'open_id'
        ]);

        $sex = $request->input('sex');
        $open_id = $request->input('open_id');
        $user_detail = UserDetail::where('open_id', $open_id)->first();

        if (!empty($user_detail->media_path)) {
            $user = User::where('id', $user_detail->user_id)->first();
            if (!empty($user->phone)) {
                return $this->renderJson(['media_path' => $user_detail->media_path]);
            } else {

                return $this->renderJson(['media_path' => '']);
            }
        }

        $weChat = new WeChat();
        $res = $weChat->buildImage($sex, $open_id);

        return $this->renderJson(['media_path' => $res]);
    }

    public function weChatUpdateImg()
    {

        $app = WeChat::getWeChatOfficialAccount();
        $path = $app->media->uploadImage(public_path('girl.jpg'));
        var_dump($path);

    }


    public function maibaoPay(Request $request)
    {
        if (!Auth::check()) {
            throw new AuthenticationException();
        }
        $this->validate($request, [
            'amount' => 'required|numeric'
        ], [
            'amount.required' => '金额不能为空',
            'amount.numeric' => '金额必须是数字'
        ]);
        $amount = $request->input('amount');
        if ($amount <= 0) {
            return $this->fail('金额错误');
        }
        if ($request->has('goods_id') && $request->input('goods_id') != '') {
            $goods = DB::table('maibao_goods')->find($request->input('goods_id'));
            if ($amount != $goods->amount) {
                return $this->fail('金额错误');
            }
        }
        if ($amount < 1000) {
            return $this->fail('充值金额不能小于1000');
        }
        $app = WeChat::getWeChatOfficialAccount();
        $url = env('weixinUrl') . '/#/user/veinCoin/';
        $app->jssdk->setUrl($url);
        $jssdk = $app->jssdk->buildConfig(array('chooseWXPay'), false, false, false);
        $out_trade_no = Util::getOrderNum();
        $data = [
            'user_id' => Auth::id(),
            'amount' => $amount,
            'order_at' => Carbon::now(),
            'appid' => $jssdk['appId'],
            'mchid' => '1453941402',
            'nonce_str' => $jssdk['nonceStr'],
            'sign' => $jssdk['signature'],
            'out_trade_no' => $out_trade_no,
            'ip' => $request->ip()
        ];
        if (!DB::table('maibao_order')->insert($data)) {
            return $this->error('系统错误');
        }
        $weChatConfig = WeChat::getWeChatPayment();
        $result = $weChatConfig->order->unify([
            'body' => '用户充值' . $amount . '脉宝',
            'out_trade_no' => $out_trade_no,
            'total_fee' => $amount * 100,
//            'total_fee' => 1,
            'trade_type' => 'JSAPI',
            'openid' => Auth::user()->detail->open_id,
            'notify_url' => env('MAIBAO_PAYMENT_CALLBACK')//'http://api.yuhongrocky.top/front/wechat/maibao_callback'//回调
        ]);
        if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
            $prepayId = $result['prepay_id']; // 这个很重要。有了这个才能调用支付。
        } else {
            return $this->error('订单生成失败');
        }
        $config = $weChatConfig->jssdk->bridgeConfig($prepayId, false);
        return $this->renderJson(['jsSdk' => $jssdk, 'payConfig' => $config]);
    }

    public function maibaoCallback()
    {
        $app = WeChat::getWeChatPayment();
        $response = $app->handlePaidNotify(function ($message, $fail) {
            $order = MaibaoOrder::where('out_trade_no', $message['out_trade_no'])->first();
            if (is_null($order) || $order->is_paid == 1) {
                return true;//已经处理过的订单
            }
            if ($message['return_code'] == 'SUCCESS') { //通信成功
                if (array_get($message, 'result_code') == 'SUCCESS') {
                    //支付成功
                    $order->is_paid = 1;
                    $order->paid_at = Carbon::now();
                    $order->status = 'paid';
                    try {
                        DB::beginTransaction();
                        //记录账单
                        $id = DB::table('maibao_bill')->insertGetId([
                            'user_id' => $order->user_id,
                            'type' => 1,
                            'title' => '微信充值',
                            'amount' => $order->amount,
                            'cate' => 3,
                            'created_at' => Carbon::now()
                        ]);
                        $user = User::where('id', $order->user_id)->lockForUpdate()->first();
                        $user->increment('maibao', $order->amount);
                        $order->bill_id = $id;
                        $order->save();
                        //添加到队列
                        DB::table('maibao_queue')->insert([
                            'user_id' => $order->user_id,
                            'amount' => $order->amount,
                            'ip' => $order->ip,
                            'created_at' => Carbon::now()
                        ]);
                        DB::commit();
                    } catch (\Exception $e) {
                        DB::rollBack();
                        return $fail('失败');
                    }
                } elseif (array_get($message, 'result_code') == 'FAIL') {
                    $order->status = 'paid_fail';
                    $order->save();
                }
            } else {
                //通信失败，一会再通知
                return $fail('通信失败，请稍后再通知我');
            }
            return true;
        });
        return $response;
    }

    public function pageTemplatePay(Request $request)
    {
        if (!Auth::check()) {
            throw new AuthenticationException();
        }
        $this->validate($request, ['clone_id' => 'required']);
        $clone = UserTemplateClone::find($request->input('clone_id'));
        $temp = UserTemplate::find($clone->template_id);
        $amount = $temp->clone_price;
        if ($amount <= 0) {
            return $this->fail('金额错误');
        }
        $app = WeChat::getWeChatOfficialAccount();
        $url = env('weixinUrl') . '/#/tools/personal/pay';
        $app->jssdk->setUrl($url);
        $jssdk = $app->jssdk->buildConfig(array('chooseWXPay'), false, false, false);
        $out_trade_no = Util::getOrderNum();
        $data = [
            'user_id' => Auth::id(),
            'amount' => $amount,
            'clone_id' => $clone->id,
            'order_at' => Carbon::now(),
            'appid' => $jssdk['appId'],
            'mchid' => '1453941402',
            'nonce_str' => $jssdk['nonceStr'],
            'sign' => $jssdk['signature'],
            'out_trade_no' => $out_trade_no
        ];

        if (!DB::table('personal_page_order')->insert($data)) {
            return $this->error();
        }
        $weChatConfig = WeChat::getWeChatPayment();
        $result = $weChatConfig->order->unify([
            'body' => '用户充值' . $amount . '脉宝',
            'out_trade_no' => $out_trade_no,
            'total_fee' => $amount * 100,
//            'total_fee' => 1,
            'trade_type' => 'JSAPI',
            'openid' => Auth::user()->detail->open_id,
            'notify_url' => env('PAGE_TEMPLATE_PAYMENT_CALLBACK')//http://api.yuhongrocky.top/front/wechat/clone_callback//回调
        ]);
        if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
            $prepayId = $result['prepay_id']; // 这个很重要。有了这个才能调用支付。
        } else {
            return $this->error('订单生成失败');
        }
        $config = $weChatConfig->jssdk->bridgeConfig($prepayId, false);
        return $this->renderJson(['jsSdk' => $jssdk, 'payConfig' => $config]);
    }

    public function cloneCallback()
    {
        $app = WeChat::getWeChatPayment();
        $response = $app->handlePaidNotify(function ($message, $fail) {

            $order = UserTemplateOrder::where('out_trade_no', $message['out_trade_no'])->first();
            if (is_null($order) || $order->is_paid == 1) {
                return true;//已经处理过的订单
            }
            if ($message['return_code'] == 'SUCCESS') { //通信成功
                if (array_get($message, 'result_code') == 'SUCCESS') {
                    \Log::info($message);
                    //支付成功
                    $order->is_paid = 1;
                    $order->paid_at = Carbon::now();
                    $order->status = 'paid';
                    $order->paid_type = '微信支付';
                    try {

                        DB::beginTransaction();
                        $clone = UserTemplateClone::find($order->clone_id);
                        //\Log::info($clone);
                        $temp = UserTemplate::find($clone->template_id);
                        //\Log::info($temp);
                        $to = User::where('id', $temp->user_id)->lockForUpdate()->first();
                        //入款
                        $to->increment('custom_income', $temp->clone_price);
                        $to->increment('money', $temp->clone_price);
                        UserBill::create([
                            'user_id' => $to->id,
                            'type' => 1,
                            'title' => "《{$temp->title}》 被克隆",
                            'amount' => $temp->clone_price
                        ]);
                        //日志
                        DB::table('personal_page_custom_clone_bill')->insert([
                            'user_id' => $to->id,
                            'type' => 1,
                            'income_type' => 2,
                            'describe' => "《{$temp->title}》 被克隆",
                            'money' => $temp->clone_price,
                            'created_at' => Carbon::now()
                        ]);
                        $clone->is_paid = 1;
                        $clone->save();
                        $order->save();
                        DB::commit();
                    } catch (\Exception $e) {
                        \Log::info($e);
                        DB::rollBack();
                        return $fail('失败');
                    }
                } elseif (array_get($message, 'result_code') == 'FAIL') {
                    $order->status = 'paid_fail';
                    $order->save();
                }
            } else {
                //通信失败，一会再通知
                return $fail('通信失败，请稍后再通知我');
            }
            return true;
        });
        return $response;
    }

    public function test()
    {
//        $weChat = new WeChat();
//        $activity_media_id  =  $weChat->getUserCode('onrTMwCTokTrzAM1CCnRoVheyfow');


    }


}
